<template>
  <div class="container">
    <div ref="topRef">
      <el-form :inline="true" :model="params" class="grids gridColumns6">
        <el-form-item
          :label="item.label"
          v-for="(item, index) in searchs"
          :key="index"
        >
          <courseTypCascader
            @fatherMethods="search"
            v-model="params[item.value]"
            v-if="item.value == 'type'"
          ></courseTypCascader>
          <courseQuery
            @fatherMethods="search"
            multiple="1"
            v-model="params[item.value]"
            v-else-if="item.value == 'curriculum_id'"
          ></courseQuery>
          <el-select
            @change="search"
            v-model="params[item.value]"
            :placeholder="`请选择${item.label}`"
            v-else-if="item.value == 'workYears'"
          >
            <el-option
              v-for="(item, index) in workYears.split(',')"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
          <dictSelect
            @fatherMethods="search"
            v-model="params.affiliation"
            dictCode="registration_affiliation"
            multiple="1"
            v-else-if="item.value == 'affiliation'"
          ></dictSelect>
          <DatePicker
            @fatherMethods="search"
            v-model="params.year"
            type="year"
            v-else-if="item.value == 'year'"
          ></DatePicker>
          <el-select
            v-else-if="item.value == 'status'"
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="2"
            multiple
            clearable
            v-model="params.status"
            placeholder="请选择订单状态"
            @change="search"
          >
            <el-option
              v-for="(item, index) in tabs"
              :key="index"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
          <el-input
            v-model="params[item.value]"
            :placeholder="`请输入${item.label}`"
            v-else
            @change="search"
          />
        </el-form-item>

        <el-form-item>
          <el-dropdown>
            <el-button type="primary">操作</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="search">查询</el-dropdown-item>
                <el-dropdown-item
                  :disabled="!selectData.length"
                  @click="proxy.$refs.editMoxueyuanRef.open(selectData)"
                  >设置课程标签</el-dropdown-item
                >
                <el-dropdown-item
                  @click="counter.exportAttachment(selectData)"
                  :disabled="!selectData.length"
                  >批量下载附件</el-dropdown-item
                >
                <el-dropdown-item
                  @click="delBatch"
                  :disabled="!selectData.length"
                  >批量删除</el-dropdown-item
                >
                <el-dropdown-item
                  @click="proxy.$refs.orderInfoExportRef.open(selectData)"
                  :disabled="!selectData.length"
                  >订单信息导出</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-button @click="dataInit" style="margin-left: 10px"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-table
      ref="tableRef"
      :data="tableData.rows"
      v-loading="loading"
      stripe
      :max-height="tableMaxHeight"
      @select-all="selectAll"
      @select="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        fixed="left"
      />
      <el-table-column label="退款时间" width="160" fixed="left">
        <template #default="scope">
          {{
            scope.row.refund_info &&
            proxy.$utils.dateTimeFormateFn(
              scope.row.refund_info.refund_time,
              "all"
            )
          }}
        </template>
      </el-table-column>

      <el-table-column
        show-overflow-tooltip
        prop="approvalContent.model.name"
        label="姓名"
        width="70"
        fixed="left"
      >
        <template #default="scope">
          <div
            class="button"
            @click="proxy.$refs.registrationDetailsRef.open(scope.row)"
          >
            {{ scope.row.approvalContent.model.name }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="approvalContent.model.mobile"
        label="联系方式"
        width="110"
        fixed="left"
      />
      <el-table-column
        prop="curriculum_Info.name"
        label="课程名称"
        width="360"
        show-overflow-tooltip
      />
      <el-table-column
        prop="approvalContent.model.identityCard"
        label="身份证号"
        width="179"
      />
      <el-table-column
        prop="approvalContent.model.graduationMajor"
        label="所在企业名称"
        width="200"
        show-overflow-tooltip
      >
        <template #default="scope">
          {{
            counter.showEnterprise(
              scope.row.approvalContent.model,
              "enterprise"
            )
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="approvalContent.model.employed_Status"
        label="就业状态"
        align="center"
        width="80"
        show-overflow-tooltip
      >
        <template #default="scope">
          {{ scope.row.approvalContent.model.employed_Status || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="approvalContent.model.workYears"
        label="累计工作年限"
        width="110"
      >
        <template #default="scope">
          {{ scope.row.approvalContent.model.workYears || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        label="最高学历"
        width="165"
        prop="approvalContent.model.education"
      />
      <el-table-column
        prop="approvalContent.model.graduationMajor"
        label="毕业专业"
        width="180"
        show-overflow-tooltip
      >
        <template #default="scope">
          {{ scope.row.approvalContent.model.graduationMajor || "-" }}
        </template>
      </el-table-column>
      <el-table-column prop="out_trade_no" label="订单号" width="170" />
      <el-table-column label="报名所属" width="150" show-overflow-tooltip>
        <template #default="scope">
          <dictSelect
            v-if="scope.row.class_Info && scope.row.class_Info.affiliation"
            v-model="scope.row.class_Info.affiliation"
            dictCode="registration_affiliation"
            readonly="1"
          ></dictSelect>
        </template>
      </el-table-column>
      <el-table-column
        prop="displayPrice"
        label="订单金额"
        align="right"
        width="80"
      >
        <template #default="scope">
          {{ proxy.$utils.formatNumber(scope.row.displayPrice) }}
        </template>
      </el-table-column>
      <el-table-column
        label="支付总计"
        width="100"
        prop="payPrice"
        align="right"
      >
        <template #default="scope">
          {{ proxy.$utils.formatNumber(scope.row.payPrice) }}
        </template>
      </el-table-column>
      <el-table-column
        label="退款理由"
        prop="refund_info.refundReason"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        label="退款单号"
        prop="refund_info.refund_id"
        width="250"
      />
      <el-table-column label="报名时间" width="180">
        <template #default="scope">
          <div class="flex alignCenter">
            {{ proxy.$utils.dateTimeFormateFn(scope.row._add_time, "all") }}
            <div v-if="scope.row.statisticsYear" class="statisticsYear fz12">
              延
            </div>
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="scope.row.class_info_show.className"
              placement="top"
              v-if="scope.row.class_info_show"
            >
              <div
                @click="
                  proxy.$utils.toLink(
                    `/classManage/classDetails?classId=${scope.row.class_info_show._id}`
                  )
                "
                class="classStatus fz12 bold"
                :class="{ active: scope.row.class_info_show.status != 2 }"
              >
                {{ scope.row.class_info_show.status == 2 ? "结" : "读" }}
              </div>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="updateUser" label="操作人" width="80">
        <template #default="scope">
          {{
            (scope.row.refund_info && scope.row.refund_info.updateUser) ||
            scope.row.updateUser
          }}
        </template>
      </el-table-column>
      <el-table-column label="退款金额" width="80" fixed="right" align="right">
        <template #default="scope">
          <div v-if="scope.row.hasOwnProperty('refundPrice')">
            {{ proxy.$utils.formatNumber(scope.row.refundPrice.toString()) }}
          </div>
          <div v-else>0</div>
        </template>
      </el-table-column>
      <el-table-column label="报名状态" width="110" fixed="right" align="right">
        <template #default="scope">
          <el-tag type="danger">已退款</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      :selectNum="selectData.length"
      v-if="tableData['total']"
      :total="tableData['total']"
      v-model:page="params.pageIndex"
      v-model:limit="params.pageSize"
      @pagination="getInfo"
      :totalPrice="total"
    />

    <registrationDetails ref="registrationDetailsRef"></registrationDetails>

    <!-- 订单信息导出 -->
    <orderInfoExport ref="orderInfoExportRef"></orderInfoExport>
  </div>
</template>

<script setup lang="ts">
//订单信息导出
import orderInfoExport from "@/views/order/components/orderInfoExport.vue";
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
const instance = getCurrentInstance();
const { proxy } = getCurrentInstance();
//订单详情
import registrationDetails from "@/views/order/components/registrationDetails.vue";

let searchs = ref([
  { label: "年份", value: "year" },
  { label: "课程名称", value: "curriculum_id" },
  { label: "姓名", value: "name" },
  { label: "联系方式", value: "mobile" },
  { label: "身份证号", value: "identityCard" },
  { label: "毕业专业", value: "graduationMajor" },
  // { label: "订单状态", value: "status" },
  { label: "订单号", value: "out_trade_no" },
  { label: "所在企业名称", value: "enterprise" },
  // { label: "培训分类", value: "type" },
  { label: "累计工作年限", value: "workYears" },
  { label: "报名所属", value: "affiliation" },
]);
let params = ref({
  pageIndex: 1,
  pageSize: 50,
  isAdmin: 1,
  curriculum_id: "",
  name: "",
  mobile: "",
  workYears: "",
  identityCard: "",
  graduationMajor: "",
  out_trade_no: "",
  affiliation: "",
  year: proxy.$utils.dateTimeFormateFn(Date.now(), "year"),
  status: [4],
});
let workYears = ref(
  "应届毕业年,不满1年,满1年,满2年,满3年,满4年,满5年,满6年,满7年,满8年,满9年,满10年及以上"
);
let selectData = ref([]); //选中的数据
let tableData = ref([]);
let loading = ref(false);
let classList = ref([]);
let topHeight = ref(0);

let total = computed(() => {
  let num = 0;
  tableData.value.rows.forEach((element) => {
    num += element.refundPrice;
  });
  return num;
});

let tableMaxHeight = computed(() => {
  let hei = window.innerHeight - 84 - counter.pageHeight - 55 - topHeight.value;
  return `${hei}px`;
});

onMounted(() => {
  class_info();
  getInfo();
  nextTick(() => {
    topHeight.value = proxy.$refs.topRef.offsetHeight;
  });
});

function dataInit() {
  params.value = {
    pageIndex: 1,
    pageSize: 50,
    status: [4],
    isAdmin: 1,
    curriculum_id: "",
    name: "",
    mobile: "",
    workYears: "",
    identityCard: "",
    graduationMajor: "",
    out_trade_no: "",
    year: proxy.$utils.dateTimeFormateFn(Date.now(), "year"),
    affiliation: "",
  };
  selectData.value = [];
  getInfo();
}

function handleSelectionChange(e, k) {
  //selectData.value = e;
  if (proxy.$utils.isFieldEqual(e, "_id", k._id)) {
    selectData.value.push(k);
  } else {
    let index = proxy.$utils.findIndexByField(selectData.value, "_id", k._id);
    if (index != -1) selectData.value.splice(index, 1);
  }
  //console.log("selectData.value", selectData.value);
}

function selectAll(array) {
  if (array.length) {
    array.forEach((element) => {
      if (proxy.$utils.isFieldEqual(selectData.value, "_id", element._id)) {
      } else {
        selectData.value.push(element);
      }
    });
  } else {
    if (tableData.value.rows && tableData.value.rows.length) {
      tableData.value.rows.forEach((element) => {
        let index = proxy.$utils.findIndexByField(
          selectData.value,
          "_id",
          element._id
        );
        if (index != -1) selectData.value.splice(index, 1);
      });
    }
  }
  //console.log("selectData.value", selectData.value);
}

async function delBatch() {
  let resp = await proxy.$utils.confirmTips("确认删除选中订单?");
  if (!resp) return;
  let list = proxy.$utils.deepcopy(selectData.value);
  for (let index = 0; index < list.length; index++) {
    const element = list[index];
    await proxy.$apis.orderAction({ type: "del", data: { _id: element._id } });
  }
  proxy.$utils.showToast("删除成功");
  getInfo("init");
}

function classIdStatus(e) {
  if (!e || !e.id) return;
  let obj = e[0];
  let index = proxy.$utils.findIndexByField(classList, "_id", obj.classId);
  if (index != -1) return classList[index];
}

//班级信息
async function class_info() {
  classList = await proxy.$apis.classData({ type: "query" });
  console.log("全部班级", classList);
}

function search() {
  params.value.pageIndex = 1;
  getInfo();
}

async function getInfo(type?) {
  try {
    loading.value = true;
    let resp = await proxy.$apis.orderAction({
      type: "list",
      data: params.value,
    });
    for (let index = 0; index < resp.rows.length; index++) {
      const element = resp.rows[index];
      if (element.class_Info && element.class_Info.classId) {
        element.class_info_show = classIdStatus(element.class_Info);
      }
    }
    tableData.value = resp;
    console.log("列表", tableData.value);
    if (type && type == "init") {
      selectData.value = [];
    } else {
      nextTick(() => {
        selectData.value.forEach((element) => {
          let a = tableData.value.rows.find((el) => {
            return element._id == el._id; // 注意这里寻找的字段要唯一，示例仅参考
          });
          if (a) proxy.$refs.tableRef.toggleRowSelection(a, true);
        });
      });
    }
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
}
</script>

<style lang="scss" scoped>
.container {
  margin: 20px;
  .statisticsYear {
    background: var(--el-color-primary);
    color: white;
    border-radius: 50%;
    margin-left: 5px;
    width: 18px;
    height: 18px;
    line-height: 18px;
    text-align: center;
  }
  .classStatus {
    border-radius: 50%;
    margin-left: 5px;
    width: 18px;
    height: 18px;
    line-height: 18px;
    text-align: center;
    color: #97999e;
    border: 1px solid #97999e;
    cursor: pointer;
  }
  .active {
    color: #3fcf66 !important;
    border: 1px solid #3fcf66 !important;
  }
}
</style>
